<template>
<div class="app-container calendar-list-container">
  <div class="content-container">
      <div style="overflow:hidden">
          <h3 class="tip">门店基本信息</h3>
          <el-col :span="16" style='margin-top:15px;'>
            <el-form :label-position="labelPosition" label-width="80px" :model="shopInfo" ref="shopInfo">
                <el-form-item label="店名">
                    <el-input v-model="shopInfo.name"></el-input>
                </el-form-item>
                <el-form-item label="店主">
                      <el-autocomplete
                      style="width: 100%;"
                        v-model="shopInfo.shopkeeper"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入内容"
                        @select="handleSelect"></el-autocomplete>
                </el-form-item>
                <el-form-item label="门店账号">
                    <el-input v-model="shopInfo.phone"></el-input>
                </el-form-item>
                <el-form-item label="门店图片">
                    <el-upload action="https://upload.qbox.me" :data="dataObj" 
                      drag :on-success="onUploadSuccess"
                      :show-file-list="false"
                      :before-upload="beforeUpload">
                      <img v-if="shopInfo.imageUrl" :src="shopInfo.imageUrl" class="avatar">
                        <div v-else>
                            <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        </div>
                      </el-upload>
                </el-form-item>
                <el-form-item label="合作方式">
                    <el-select class="filter-item" v-model="shopInfo.operateType" placeholder="请选择合作方式" @change="change" style="width:100%;">
                            <el-option v-for="item in  operateArray" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="自带机器">
                    <el-radio-group v-model="shopInfo.zdMachine">
                      <el-radio :label="true">是</el-radio>
                      <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="自带厂房">
                    <el-radio-group v-model="shopInfo.hasWorkShop">
                      <el-radio :label="true">是</el-radio>
                      <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="自带货车">
                    <el-radio-group v-model="shopInfo.zdTran">
                      <el-radio :label="true">是</el-radio>
                      <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="地区">
                    <div class="amap-page-container">
                      <el-amap-search-box 
                        class="search-box" 
                        :search-option="searchOption" 
                        :on-search-result="onSearchResult">
                      </el-amap-search-box>
                      <el-amap 
                        vid="amapDemo" 
                        :center="center" 
                        :zoom="zoom" 
                        class="amap-demo"
                        :plugin="plugin">
                        <el-amap-marker
                          :position="center" >
                        </el-amap-marker>
                      </el-amap>
                    </div>
                </el-form-item>
                <el-form-item label="详细地址">
                    <el-input v-model="shopInfo.dtlAddress"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="shopInfo.description"></el-input>
                </el-form-item>
                <el-form-item v-if="formStatus == 'update'">
                    <el-button type="primary"   @click="update">更新</el-button>
                    <el-button @click="onCancel">取消</el-button>
                </el-form-item>
                <el-form-item v-if="formStatus == 'create'">
                    <el-button type="primary"   @click="create">保存</el-button>
                    <el-button @click="onCancel">取消</el-button>
                </el-form-item>
            </el-form>
          </el-col>
        </div>
        <div style="overflow:hidden" v-if="$route.query.id">
          <h3 class="tip">加工商区域</h3> 
          <el-button type="primary" style="margin-bottom:20px"   @click="handleCreate">添加</el-button>
          
          <el-table :key='regionKey' :data="communityList" v-loading.body="listLoading" border fit highlight-current-row >
              <el-table-column align="center" label="编号" width="65"> <template scope="scope">
                    <span>{{scope.row.id}}</span>
                  </template> </el-table-column>
              <el-table-column width="250" align="center" label="小区名称"> <template scope="scope">
                  <span>{{scope.row.name}}</span>
                </template> </el-table-column>
              <el-table-column width="300" align="center" label="物业"> <template scope="scope">
                      <span>{{scope.row.property}}</span>
                    </template> </el-table-column>
              <el-table-column width="100" align="center" label="年份"> <template scope="scope">
                      <span>{{scope.row.years}}</span>
                    </template> </el-table-column>
              <el-table-column width="100" align="center" label="等级"> <template scope="scope">
                      <span>{{scope.row.level}}</span>
                    </template> </el-table-column>      
              <el-table-column  align="center" label="备注"> <template scope="scope">
                      <span>{{scope.row.remark}}</span>
                    </template> </el-table-column>      
              <el-table-column align="center" label="操作" width="250" fixed="right"> <template slot-scope="scope"> 
                <el-button   size="small" type="success" @click="handleUpdate(scope.row)">编辑
                </el-button>
                <el-button  size="small" type="danger" @click="handleDelete(scope.row)">删除
                </el-button>
              </template> </el-table-column>      
            </el-table>
        </div>
        <div style="overflow:hidden" v-if="$route.query.id">
          <h3 class="tip">门店订单</h3> 
          <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%" @row-click="onOrderItemClick">
              <el-table-column align="center" label="编号" width="65"> <template scope="scope">
                    <span>{{scope.row.id}}</span>
                  </template> </el-table-column>
              <el-table-column width="200" align="center" label="姓名"> <template scope="scope">
                  <span>{{scope.row.name}}</span>
                </template> </el-table-column>
              <el-table-column width="200" align="center" label="电话"> <template scope="scope">
                      <span>{{scope.row.phone}}</span>
                    </template> </el-table-column>
              <el-table-column width="300" align="center" label="客户需求"> <template scope="scope">
                      <span>{{scope.row.demand}}</span>
                    </template> </el-table-column>
              <el-table-column width="300" align="center" label="地址"> <template scope="scope">
                      <span>{{scope.row.dtladdress}}</span>
                    </template> </el-table-column>      
              <el-table-column width="180" align="center" label="订单生成时间"> <template scope="scope">
                    <span>{{scope.row.createTime}}</span>
                  </template> </el-table-column>    
              <el-table-column width="180" align="center" label="订单状态"> <template scope="scope">
                    <el-tag v-if="scope.row.status == 0" type="danger">待处理</el-tag>
                    <el-tag v-if="scope.row.status !== 0 && scope.row.status !== 13" >进行中</el-tag>
                    <el-tag v-if="scope.row.status == 13" type="info">已结束</el-tag>
                  </template> </el-table-column>
            </el-table>
        </div>
      </div>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="小区名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入小区名称"></el-input>
          </el-form-item>
          <el-form-item label="物业" prop="property">
            <el-input v-model="form.property" placeholder="请输入所属物业"></el-input>
          </el-form-item>
          <el-form-item label="年份">
            <el-input v-model="form.years" placeholder="请输入年份,如:1"></el-input>
          </el-form-item>
          <el-form-item label="等级">
            <el-input v-model="form.level" placeholder="请输入等级,如:5"></el-input>
          </el-form-item>
          
          <el-form-item label="备注">
            <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 5}" placeholder="请输入备注" v-model="form.remark"> </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('form')">取 消</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="addOrUpdateCommunityAction('form')">确 定</el-button>
          <el-button v-else type="primary" @click="addOrUpdateCommunityAction('form')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import { searchByKw } from "@/api/user/index";
import { shopItem, shopList, addOrUpdate } from "@/api/shop/index";
import { mapGetters } from "vuex";
import { getToken } from "@/api/qiniu";
import { itemWithSubLevel, subList } from "@/api/district/index";
import { listByShop } from "@/api/order/index";
import {
  communityList,
  getObj,
  addOrUpdateCommunity,
  delObj
} from "@/api/community/index";

export default {
  name: "user",
  data() {
    let vm = this;
    return {
      zoom: 12,
      center: [121.329402, 31.228667],
      searchOption: {
        cityName: "无锡",
        citylimit: false
      },
      result: [],
      plugin: [
        {
          pName: "ToolBar", //工具条插件
          position: "LB"
        },
        {
          pName: "OverView"
          //isOpen:true//鹰眼是否打开
        },
        {
          pName: "Scale"
        },
        {
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 100, //超过10秒后停止定位，默认：无穷大
          maximumAge: 0, //定位结果缓存0毫秒，默认：0
          convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: "RB", //定位按钮停靠位置，默认：'LB'，左下角
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
          extensions: "all",
          pName: "Geolocation", //定位插件
          showMarker: false,
          events: {
            init(o) {
              //定位成功 自动将marker和circle移到定位点
              o.getCurrentPosition((status, result) => {
                console.log(result);
                if (result && result.position) {
                  vm.center = [result.position.lng, result.position.lat];
                  vm.$nextTick();
                }
              });
            }
          }
        }
      ],
      form: {},
      phoneDisable: false,
      imageUrl: "",
      dataObj: { token: "", key: "" },
      operateArray: [
        {
          id: 0,
          name: "直营店"
        },
        {
          id: 1,
          name: "加盟店"
        },
        {
          id: 2,
          name: "协议店"
        }
      ],
      province: "",
      city: "",
      area: "",
      street: "",
      labelPosition: "right",
      formStatus: "create",
      rules: {},
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20
      },
      communityList: [],
      sexOptions: ["男", "女"],
      dialogFormVisible: false,
      dialogStatus: "",
      userManager_btn_edit: true,
      userManager_btn_del: true,
      userManager_btn_add: true,
      textMap: {
        update: "编辑",
        create: "创建"
      },
      regionKey: 1,
      tableKey: 0,
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      image: "",
      file: "",
      shopInfo: {
        id: null,
        phone: "",
        name: "",
        provinceId: 355,
        cityId: 356,
        areaId: 357,
        streetId: 358,
        slogan: null,
        description: null,
        shopkeeper: "",
        userId: null,
        longtitude: null,
        latitude: null,
        operateType: 0,
        imageUrl: "",
        zdMachine: true,
        zdTran: true,
        hasWorkShop: false
      }
    };
  },
  created() {
    //加载店铺信息
    if (this.$route.query.id) {
      this.loadShopItem();
    } else {
    }
    this.getList();
    this.communityListAction();
  },
  computed: {
    ...mapGetters(["elements"])
  },
  methods: {
    onSearchResult(pois) {
      this.result = pois;
      let latSum = 0;
      let lngSum = 0;
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        };
        this.center = [center.lng, center.lat];
      }
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    addCommunityAction() {},
    communityListAction() {
      communityList(this.$route.query.id).then(resp => {
        this.communityList = resp.data;
        console.log(this.communityList);
      });
    },
    onOrderItemClick(row, event, column) {
      if (row.status == 0) {
        return;
      }
      this.$router.push({
        name: "order_item",
        query: {
          id: row.id
        }
      });
    },
    getList() {
      if (this.$route.query.id) {
        var param = {
          id: this.$route.query.id
        };
        listByShop(param).then(response => {
          this.list = response.data;
          this.listLoading = false;
        });
      }
    },
    loadShopItem() {
      var param = {
        id: this.$route.query.id
      };

      shopItem(param).then(resp => {
        this.shopInfo = resp.data;
      });
    },
    onShopKeeperChange(val) {
      this.phoneDisable = false;
    },
    querySearchAsync(queryString, cb) {
      searchByKw(queryString).then(res => {
        if (res.data) {
          var arrResult = [];
          res.data.forEach(element => {
            var item = {
              value: element.name,
              key: element.phone
            };
            arrResult.push(item);
          });
          cb(arrResult);
        }
      });
    },
    handleSelect(item) {
      console.log(item);
      if (this.shopInfo.shopkeeper != "") {
        this.phoneDisable = true;
      }
      this.shopInfo.phone = item.key;
    },
    onUploadSuccess(response, file, fileList) {
      this.$set(
        this.shopInfo,
        "imageUrl",
        "http://p8x2p1gru.bkt.clouddn.com/" + response.key
      );
    },
    beforeUpload(file) {
      const _self = this;
      return new Promise((resolve, reject) => {
        getToken()
          .then(response => {
            console.log(response);
            const token = response.data;
            _self._data.dataObj.token = token;
            _self._data.dataObj.key = file.name;
            resolve(true);
          })
          .catch(err => {
            console.log(err);
            reject(false);
          });
      });
    },
    change() {},
    onCancel() {
      this.$router.go(-1);
    },

    handleUpdate(row) {
      getObj(row.id).then(response => {
        this.form = response.data;
        this.dialogFormVisible = true;
        this.dialogStatus = "update";
      });
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delObj(row.id).then(resp => {
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
          this.communityListAction();
        });
      });
    },
    create(formName) {
      this.shopInfo.longtitude = this.center[0]
      this.shopInfo.latitude = this.center[1]
      var shopParam = {
        shop: this.shopInfo
      };
      addOrUpdate(shopParam).then(resp => {
        this.dialogFormVisible = false;
        this.$notify({
          title: "提示",
          type: "success",
          message: resp.message,
          duration: 2000
        });

        this.$router.push({
          name: "shop",
      });
        
      });
    },

    isRealNum(val) {
      if (val === "" || val == null) {
        return false;
      }
      if (!isNaN(val)) {
        return true;
      } else {
        return false;
      }
    },
    addOrUpdateCommunityAction(formName) {
      var param = {
        community: this.form
      };
      if(!this.isRealNum(this.form.years)){
        this.$message({
          message: '年份必须为纯数字',
          type: 'warning'
        });
        return
      }
      if(!this.isRealNum(this.form.level)){
        this.$message({
          message: '小区等级必须为纯数字',
          type: 'warning'
        });
        return
      }

      addOrUpdateCommunity(this.form).then(resp => {
        this.dialogFormVisible = false;
        this.$notify({
          title: "提示",
          message: resp.message,
          type: "success",
          duration: 2000
        });
        this.communityListAction();
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          this.form.password = undefined;
          putObj(this.form.id, this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },
    resetTemp() {
      this.form = {
        username: undefined,
        id: undefined,
        shopId: this.$route.query.id,
        name: undefined,
        sex: "男",
        password: undefined,
        description: undefined,
        years: undefined,
        level: undefined,
        street: undefined,
        streetId: null,
        areaId: null,
        cityId: null,
        provinceId: null,
        remark: undefined,
        property: undefined
      };
    }
  }
};
</script>
<style scoped>
.content-left {
  float: left;
}
.content-right {
  height: 100px;
  border: 1px solid #ff0000;
  float: left;
  margin-left: 20px;
}

.tip {
  padding: 8px 16px;
  background-color: #f5f5f5;
  border-left: 5px solid #42b983;
  margin: 20px 0;
  color: #757575;
}

.avatar {
  width: 180px;
  height: 180px;
}

.amap-page-container {
  height: 600px;
  position: relative;
}
.search-box {
  position: absolute !important;
  top: 10px;
  left: 20px;
}
</style>